﻿/**
* This program is distributed "as-is" and is not
* documented beyond the scope of the source-code
* comments.											
*
* @author:	JR Lanteigne
* @class:	JET 1 Spring 2014
* @title:	LED_RESISTOR.c
*/

#include "stdio.h"	// printf, scanf
#include "stdlib.h"	// system()
#include "cmath"	// abs()

/**
* Solves resistance for LED
*
* @param	v_forward	Diode forward voltage (Volts)
* @param	v_supply	Power supply voltage (Volts)
* @param	i_led		Design current of LED (Amps)
* @return	(double) ohm's law, or error -1
*/
double solveResistance(double v_forward, double v_supply, double i_led) {
	double resistance;
	/* FORWARD VOLTAGE: The voltage at which the diode becomes forward biased.
						On a diode V-I plot, the point which corresponds to Vf
						and If is always in Quadrant I. THUS, Vf and If must
						be positive by their very definition. Vsupply, however,
						is a design value which may be (incorrectly) negative.
	*/
	i_led = abs(i_led);
	v_forward = abs(v_forward);

	if(v_supply < v_forward) {
		resistance = -1; // v_supply must be greater than v_forward!
	} else {
		resistance = (v_supply - v_forward)/i_led; // ohm's law
	}
	return resistance;
}

int main(int argc, char *argv[]) {
	// loop exit parameter
	int __done = 0;
	
	// init variables
	double resistor_value, forward_voltage, supply_voltage, led_current;

	// print program header
	printf("\n        LED RESISTOR HELPER\n%s%s%s%s%s",
		"\n==================================================\n",
		"   PROG1018 : JR Lanteigne (JET 1)\n",
		"   FOR: Mr J. Murray\n",
		"==================================================\n",
		"\nEnter the following values to solve for R\n");

	// evaluate condition for loop to continue, ends when successful
	while(!__done) {
		// ask for user input before attempting to solve
		printf("\nLED Forward Voltage Drop (V): \t");
		scanf("%lf", &forward_voltage);
		printf("\nLED Design Current (mA): \t");
		scanf("%lf", &led_current);
		printf("\nSupply Voltage (V): \t\t");
		scanf("%lf", &supply_voltage);

		// call solveResistance with given values
		resistor_value = solveResistance(forward_voltage, supply_voltage, led_current/1000);
		if(resistor_value != -1) {
			printf("\n\nYou should select resistors that combine to: %d ohms\n", (int) resistor_value); // success
			__done = 1;
		} else
			printf("\nERROR: Supply voltage must be greater than diode forward voltage.\n"); // user should review diode theory
	}
	// exit program nicely
	// for win32 console, add CR and exit
	system("echo. && pause");
	// for linux shell
	// system("read -p \"Press [ENTER] to quit.\");

	return 0;
}

